<template>
    <MyDialog ref="myDialog" title="新增品类" width="600px" :on-confirm="confirm" :on-cancel="clearData">
        <MyForm ref="myForm" label-width="124px" :form-data="formData" :form-item-list="formItemList" :form-rules="formRules"></MyForm>
    </MyDialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
interface FormData {
    id?: string;
    parentId?: string;
    chineseName: string;
    englishName?: string;
    icon?: MyComment.FormUploadValue;
    iconId?: string;
    fileId: string;
}

const emit = defineEmits<{
    (event: 'complete', id: boolean): void;
}>();

const formData: FormData = {
    parentId: '',
    chineseName: '',
    englishName: '',
    icon: null,
    iconId: '',
    fileId: '',
};

const formItemList = ref<MyComment.FormItemProps<FormData>[]>([
    {
        prop: 'chineseName',
        label: '品类中文全称',
        contentProps: { maxlength: 10, placeholder: '请输入品类中文全称' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'englishName',
        label: '品类英文全称',
        contentProps: { maxlength: 10, placeholder: '请输入品类英文全称' } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'icon',
        label: '品类ICON',
        type: 'upload',
        contentProps: { accept: '.png,.jpg' } as MyComment.FormItemContentProps['upload'],
        contentExtends: { placeholder: '尺寸400X400，大小不超过100kb' } as MyComment.FormItemContentExtends['upload'],
    },
    {
        prop: 'fileId',
        label: '品类Profile',
        type: 'select',
        data: [],
        contentProps: { placeholder: '请选择Profile' } as MyComment.FormItemContentProps['select'],
    },
]);

const formRules: MyComment.FormRules<FormData> = {
    chineseName: { required: true, trigger: 'blur', message: '请输入品类中文全称' },
    icon: { trigger: 'change', type: 'file', fileSize: 1024 * 100, fileAccept: ['.png', '.jpg'] },
    fileId: { required: true, trigger: 'change', message: '请选择Profile' },
};

const myDialog = ref<MyComment.DialogInstance>();
const myForm = ref<MyComment.FormInstance<FormData>>();

const getProfileList = async () => {
    const res = await MyService.product.getProfileAllList({ searchKey: '' });
    if (res.code === 200) {
        formItemList.value[3].data = res.data.map((item) => ({ label: item.name, value: item.fileId || '' }));
    } else {
        formItemList.value[3].data = [];
    }
};

const confirm = async (): Promise<boolean> => {
    if (myForm.value) {
        const validateResult = await myForm.value.validate();
        if (validateResult) {
            const data = myForm.value.getData();
            const submitData = { ...data, icon: undefined };
            if (data.icon && data.icon instanceof File) {
                const uploadIconRes = await MyService.product.updateCategoryIcon({ file: data.icon });
                if (uploadIconRes.code === 200 && uploadIconRes.data) {
                    submitData.iconId = uploadIconRes.data;
                } else {
                    ElMessage.error({
                        message: uploadIconRes.msg || '上传品类ICON失败',
                    });
                    emit('complete', false);
                    return false;
                }
            } else {
                if (data.icon === null) {
                    submitData.iconId = '';
                }
            }
            let submitRes: any = {};
            if (submitData.id) {
                submitRes = await MyService.product.updateCategory(submitData);
            } else {
                submitRes = await MyService.product.createCategory(submitData);
            }
            if (submitRes.code === 200) {
                emit('complete', true);
                return true;
            } else {
                ElMessage.error({
                    message: submitRes.msg || submitData.id ? '编辑品类失败' : '创建品类失败',
                });
                emit('complete', false);
                return false;
            }
        } else {
            emit('complete', false);
            return false;
        }
    }
    emit('complete', false);
    return false;
};

const open = (isEdit: boolean, data: any) => {
    myDialog.value?.open();
    setTimeout(() => {
        if (isEdit) {
            myForm.value?.setData(data);
        } else {
            formData.parentId = data as string;
            myForm.value?.setData(formData);
        }
        getProfileList();
    }, 50);
};

const clearData = () => {
};

defineExpose({
    open,
});
</script>

<style scoped></style>
